package 寒假刷题;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class 最小高度树 {

    public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        List<Integer> res = new ArrayList<>();
        //树的高度为1
        if (n==1){
            res.add(0);
            return res;
        }
        //统计每个节点的度
        int[] degree = new int[n];
        List<List<Integer>> map= new ArrayList<>();
        for (int i = 0; i < n; i++) {
            map.add(new ArrayList<>());
        }
        for (int[] edge : edges) {
            degree[edge[0]]++;
            degree[edge[1]]++;
            map.get(edge[0]).add(edge[1]);
            map.get(edge[1]).add(edge[0]);
        }
        Queue<Integer> queue = new LinkedList<>();
        //将度为1的节点添加到队列中
        for (int i = 0; i < n; i++) {
            if (degree[i]==1)
                queue.add(i);
        }
        while (!queue.isEmpty()){
            res = new ArrayList<>();
            int size = queue.size();
            for (int i = 0; i <size; i++) {
                Integer poll = queue.poll();
                res.add(poll);
                List<Integer> neighbors = map.get(poll);
                for (Integer neighbor : neighbors) {
                    degree[neighbor]--;
                    if (degree[neighbor]==1)
                        queue.add(neighbor);
                }
            }
        }
        return res;
    }
}
